package com.example.rbacmanage.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;

public class HttpClientUtil {
    public static String doGet(String url, Map<String,String> params,Map<String,String> headers) {
        if (url == null) {
            return null;
        }
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String paramsStr = "";
        try{
            List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();
            if (params != null) {
                for (String key : params.keySet()) {
                    paramsList.add(new BasicNameValuePair(key, params.get(key)));
                }
                paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(paramsList));
            }
            StringBuffer sb = new StringBuffer();
            sb.append(url);
            if (params != null) {
                sb.append("?");
                sb.append(paramsStr);
            }
            HttpGet httpGet = new HttpGet(sb.toString());
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000)
                    .setConnectTimeout(2000).build();
            httpGet.setConfig(requestConfig);
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpGet.addHeader(key, headers.get(key));
                }
            }
            response=httpClient.execute(httpGet);
            int statusCode=response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != statusCode) {
                httpGet.abort();
                throw new RuntimeException("HttpClient, error status code: " + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }


    public static byte[] doPostJsonReturnByte(String url, Map<String, Object> paraMap) {
        byte[] result = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        try {
            // 设置请求的参数
            JSONObject postData = new JSONObject();
            for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
                postData.put(entry.getKey(), entry.getValue());
            }
            httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toByteArray(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }

    public static String doPostJsonReturnString(String url, String params, Map<String,String> headers) {
        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try{
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000)
                    .setConnectTimeout(2000).build();
            httpPost.setEntity(new StringEntity(params, ContentType.APPLICATION_JSON));
            httpPost.setConfig(requestConfig);
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }
            response=httpClient.execute(httpPost);
            int statusCode=response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != statusCode) {
                httpPost.abort();
                throw new RuntimeException("HttpClient, error status code: " + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        return result;
    }




    /**
     * 发送HTTP POST请求（使用表单数据）。
     * 该方法用于通过POST方式发送表单数据到指定的URL，并返回响应结果。
     *
     * @param url        请求的URL地址。不能为空。
     * @param params     请求的参数，以键值对形式提供。可以为空，但如果非空，则以表单数据形式发送。
     * @param headParams 请求的头部参数，以键值对形式提供。可以为空，但如果非空，则添加到请求头中。
     * @return           服务器响应的字符串形式内容。如果请求失败，则可能返回null。
     */
    public static String doPostFormData(String url, Map<String, String> params, Map<String, String> headParams) {
        String result = null;
        // 创建HTTP客户端实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            // 创建HTTP POST请求对象
            HttpPost httpPost = new HttpPost(url);

            // 配置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
            httpPost.setConfig(requestConfig);

            // 如果存在请求参数，则将其转换为表单实体，并设置到请求对象中
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> paramsList = new ArrayList<>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramsList, "UTF-8");
                httpPost.setEntity(urlEncodedFormEntity);
            }

            // 如果存在头部参数，则添加到请求头中
            if (headParams != null && !headParams.isEmpty()) {
                for (Map.Entry<String, String> entry : headParams.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            // 执行请求并获取响应
            response = httpClient.execute(httpPost);

            // 检查响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != statusCode) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }

            // 从响应中获取内容并转换为字符串
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 无论成功或失败，都关闭资源
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        return result;
    }

}


